import React from 'react';
import classNames from 'classnames';

export default class FormItem extends React.Component {
  constructor(props) {
    super(props);

    this.isRequired = this.isRequired.bind(this);
    this.renderLabel = this.renderLabel.bind(this);
  }

  isRequired() {
    const { required } = this.props;
    if (required !== undefined) {
      return required;
    }

    return false;
  }

  renderLabel() {
    const { label, id } = this.props;
    const required = this.isRequired();

    const className = classNames('control-label', {
      ['item-required']: required,
    });

    let labelChildren = label;

    labelChildren = label.replace(/[：|:]\s*$/, ':');
    return label ? (
      <label
        htmlFor={id}
        className={className}
        // title={typeof label === 'string' ? label : ''}
      >
        {labelChildren}
      </label>
    ) : null;
  }

  render() {
    const { errorMsg } = this.props;
    return (
      <div className="form-group">
        {this.renderLabel()}
        <div className="form-control">
          {this.props.children}
        </div>
        <div className="error">
          <p>{errorMsg}</p>
        </div>
      </div>
    );
  }
}